package org.budo.mongo.jdbc.driver.statement;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.budo.jdbc.driver.AbstractBudoJdbcPreparedStatement;
import org.budo.jdbc.driver.statement.AbstractJdbcStatement;
import org.budo.mongo.jdbc.driver.BudoMongoJdbcConnection;
import org.budo.mongo.jdbc.driver.executor.MongoStatementExecutor;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author li
 */
@Getter
@Setter
@Slf4j
public abstract class AbstractMongoStatement extends AbstractJdbcStatement implements MongoStatement {
    private ParameterProcessor parameterProcessor = new ParameterProcessor();

    private String collectionName;

    private String statementJson;

    private ResultSetMetaData resultSetMetaData;

    private ResultSet resultSet;

    private int updateCount;

    protected MongoStatementExecutor statementExecutor(PreparedStatement preparedStatement) throws SQLException {
        Connection connection = preparedStatement.getConnection();
        BudoMongoJdbcConnection mongoConnection = (BudoMongoJdbcConnection) connection;
        return mongoConnection.statementExecutor();
    }

    protected StatementDocument statementDocument(PreparedStatement preparedStatement) {
        Map<Integer, Object> parameterMap = ((AbstractBudoJdbcPreparedStatement) preparedStatement).getParameterMap();
        String statementJson = this.getStatementJson();

        return new StatementDocument(statementJson, parameterMap);
    }

    protected String statementJson(PreparedStatement preparedStatement) {
        Map<Integer, Object> parameterMap = ((AbstractBudoJdbcPreparedStatement) preparedStatement).getParameterMap();
        String statementJson = this.getStatementJson();

        List<Date> parameterTemp = new ArrayList<Date>();
        String statementParameterized = parameterProcessor.statementParameterize(statementJson, parameterMap, parameterTemp);

        log.debug("#52 statementJson={}", statementParameterized);
        return statementParameterized;
    }

    public String toString() {
        return super.toString() + ", statementJson=" + this.getStatementJson() + ", collectionName=" + this.getCollectionName();
    }
}